<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      label-position="right"
      label-width="80px"
      :model="user"
      :rules="formDataRules"
      ref="formRef"
    >
      <el-form-item label="登录名称">
        <el-input disabled v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="doSubmit">提交修改</el-button>
        <el-button type="info" @click="resetBtn">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  //数据
  data() {
    return {
      //将vuex的数据拷贝到data中
      user: { ...this.$store.state.user },
      //定义校验规则
      formDataRules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            pattern: /^\S{1,10}$/,
            message: "昵称必须是1-10位的非空字符串",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
      },
    };
  },
  //方法
  methods: {
    //提交修改
    doSubmit() {
      //判断表单校验是否通过
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          //发送请求
          const { data: res } = await this.$axios.put(
            "/my/userinfo",
            this.user
          );
          this.$message.success(res.message);
          //提交actions更新用户数据
          this.$store.dispatch("getUserInfo");
        }
      });
    },
    //重置按钮
    resetBtn(){
      //恢复到表单组件初始的状态
      this.$refs.formRef.resetFields()
    }
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
